#include "base_socket.h"

int32_t BaseSocket::CreateSocket(const int32_t _af, const int32_t _type, const int32_t _protocol)
{
    int32_t _fd = socket(_af, _type, _protocol);
    if (_fd < 0)
    {
        perror("create socket failed.\n");
        exit(-1);
    }
    return _fd;
}

void BaseSocket::CloseSocket(int32_t _fd)
{
    if (_fd <= 0)
        return;
    close(_fd);
}

void BaseSocket::SetNonBlackSocket(int32_t _fd, bool _block)
{
    int32_t flag = fcntl(_fd, F_GETFL, 0);
    if (_block)
    {
        int32_t ret = fcntl(_fd, F_SETFL, flag | O_NONBLOCK);
        if (ret == -1)
        {
            perror("set socket nonblack failed.\n");
        }
    }
    else
    {
        int32_t ret = fcntl(_fd, F_SETFL, flag & ~O_NONBLOCK);
        if (ret == -1)
        {
            perror("set socket blacking failed.\n");
        }
    }
}

bool BaseSocket::GetNonBlackModel(int32_t _fd)
{
    int32_t flag = fcntl(_fd, F_GETFL, 0);
    if (flag == -1)
        return;
    return flag > 0;
}

void BaseSocket::SetRecvBuffSize(int32_t _fd, uint32_t _size)
{
    if (setsockopt(_fd, SOL_SOCKET, SO_RCVBUF, &_size, sizeof(uint32_t)) < 0)
    {
        perror("setsockopt SO_RCVBUF failed.\n");
    }
}

void BaseSocket::SetSendBuffSize(int32_t _fd, uint32_t _size)
{
    if (setsockopt(_fd, SOL_SOCKET, SO_SNDBUF, &_size, sizeof(uint32_t)) < 0)
    {
        perror("setsockopt SO_SNDBUF failed.\n");
    }
}

int32_t BaseSocket::GetRecvBuffSize(int32_t _fd)
{
    int32_t buf_size = 0;
    socklen_t opt_len = sizeof(buf_size);
    // 获取当前接收缓冲区大小
    if (getsockopt(_fd, SOL_SOCKET, SO_RCVBUF, &buf_size, &opt_len) < 0)
    {
        perror("getsockopt SO_RCVBUF failed.\n");
    }
    return buf_size;
}

int32_t BaseSocket::GetSendBuffSize(int32_t _fd)
{
    int32_t buf_size = 0;
    socklen_t opt_len = sizeof(buf_size);
    if (getsockopt(_fd, SOL_SOCKET, SO_SNDBUF, &buf_size, &opt_len) < 0)
    {
        perror("getsockopt SO_SNDBUF failed.\n");
    }
    return buf_size;
}
